<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 试验计划详情 -->
    <div
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="spinning">
        <!-- 项目信息 -->
        <a-card :bordered="false">
          <title-name title="项目信息" />
          <a-form-model
            ref="ruleForm"
            :model="projectInfo"
            :rules="editModel == 2 ? {} : rules"
            :label-col="{ span: 9 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-row>
              <a-col :span="16">
                <a-form-model-item
                  label="所属单位"
                  prop="projectId"
                >
                  <org-tree-select
                    is-need-auth
                    :southwestCompany="editModel==2? true: false"
                    :is-auto-select-first="editModel==0"
                    check-strictly
                    :disabled="editModel == 2"
                    v-model="projectInfo.projectId"
                    @select="selectOrg"
                  ></org-tree-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
        <!-- 表格 -->
        <a-card
          :bordered="false"
          style="margin-bottom: 50px"
        >
          <title-name title="试验信息" />
          <a-form-model
            ref="experimentForm"
            :model="experimentTable"
            :rules="editModel == 2 ? {} : rules"
            :label-col="{ span: 9 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  label="试件编号"
                  prop="specimenNumber"
                >
                  <BaseInput
                    v-model="experimentTable.specimenNumber"
                    :max-length="30"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="试验计划">
                  <a-row
                    type="flex"
                    align="middle"
                  >
                    <div :style="{ width: editModel == 2 ? '100%' : 'calc(100% - 138px)' }">
                      <BaseInput
                        v-model="planItems"
                        disabled
                      />
                    </div>
                    <a-button
                      v-if="editModel != 2"
                      type="primary"
                      class="ml12"
                      icon="link"
                      :loading="requestLoading"
                      :disabled="!projectInfo.projectId"
                      @click="handleOpen()"
                    >
                      关联计划项
                    </a-button>
                  </a-row>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="规格"
                  prop="specification"
                >
                  <BaseInput
                    v-model="experimentTable.specification"
                    placeholder="请输入"
                    :disabled="editModel == 2 || selectedRowKeys.length > 0"
                    @change="
                      $set(experimentTable, 'details', [])
                      $set(experimentTable, 'place', void 0)
                    "
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  label="试验项目"
                  prop="experimentProject"
                >
                  <selector
                    v-model="experimentTable.experimentProject"
                    select-type="6"
                    placeholder="请选择"
                    :disabled="editModel == 2 || selectedRowKeys.length > 0"
                    @getOption="
                      (e) => {
                        $set(experimentTable, 'experimentProjectName', e ? e.name:'')
                      }
                    "
                    @change="
                      $set(experimentTable, 'details', [])
                      $set(experimentTable, 'place', void 0)
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <div v-if="experimentTable.experimentProjectName && experimentTable.experimentProjectName.indexOf('其他') > -1">
                  <a-form-model-item prop="otherExperimentProjectName" label="" class="requiredFormItem">
                    <BaseInput
                      style="margin-left: 20px;"
                      placeholder="请输入具体的试验项目种类"
                      :maxLength="30"
                      :disabled="editModel == 2 || (selectedRow.length > 0 && !!selectedRow[0].otherExperimentProjectName)"
                      v-model="experimentTable.otherExperimentProjectName"
                    />
                  </a-form-model-item>
                </div>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="品种/种类"
                  prop="varietiesKinds"
                >
                  <BaseInput
                    v-model="experimentTable.varietiesKinds"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  label="产地厂别"
                  prop="originSite"
                >
                  <BaseInput
                    v-model="experimentTable.originSite"
                    :max-length="30"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="部位"
                  prop="place"
                >
                  <BaseInput
                    v-model="experimentTable.place"
                    :max-length="30"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="是否见证"
                  prop="whetherToWitness"
                >
                  <a-select
                    v-model="experimentTable.whetherToWitness"
                    placeholder="请选择"
                    :disabled="editModel == 2"
                  >
                    <a-select-option value="0">
                      否
                    </a-select-option>
                    <a-select-option value="1">
                      是
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="进场时间"
                  prop="entryTime"
                >
                  <a-date-picker
                    v-if="editModel != 2"
                    v-model="experimentTable.entryTime"
                    value-format="YYYY-MM-DD"
                  />
                  <BaseInput
                    v-else
                    v-model="experimentTable.entryTime"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="送检时间"
                  prop="inspectionTime"
                >
                  <a-date-picker
                    v-if="editModel != 2"
                    v-model="experimentTable.inspectionTime"
                    value-format="YYYY-MM-DD"
                  />
                  <BaseInput
                    v-else
                    v-model="experimentTable.inspectionTime"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="委托编号"
                  prop="principalNo"
                >
                  <BaseInput
                    v-model="experimentTable.principalNo"
                    :max-length="30"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="报告编号"
                  prop="reportNo"
                >
                  <BaseInput
                    v-model="experimentTable.reportNo"
                    :max-length="30"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="试验结果"
                  prop="experimentResults"
                >
                  <selector
                    v-model="experimentTable.experimentResults"
                    select-type="7"
                    placeholder="请选择"
                    :disabled="editModel == 2"
                    @getOption="
                      (e) => {
                        $set(experimentTable, 'experimentResults', e ? e.id:'')
                        $set(experimentTable, 'experimentResultsName', e ? e.name:'')
                      }
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="归档时间"
                  prop="archiveTime"
                >
                  <a-date-picker
                    v-if="editModel != 2"
                    v-model="experimentTable.archiveTime"
                    value-format="YYYY-MM-DD"
                  />
                  <BaseInput
                    v-else
                    v-model="experimentTable.archiveTime"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="试验报告"
                  prop="fileArrays"
                >
                  <upload-list
                    v-if="editModel != 2"
                    business-code="PM04"
                    :upload-arrys.sync="experimentTable.fileArrays"
                  />
                  <file-link
                    v-else
                    :file-list="experimentTable.fileArrays"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <!-- <div class="btn_box page-btn-right-top" style="position: fixed; bottom: 0; right: 50px; height: 50px; display: flex; align-items: center"> -->
        <a-button
          v-if="editModel != 2"
          :loading="loading"
          type="primary"
          class="button_right"
          @click="handleSubmit"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="$multiTab.close()"
        >
          关闭
        </a-button>
      </div>
    </div>
    <!-- 选择试验项目 -->
    <DialogForm
      ref="dialogForm"
      :custom-footer="true"
      header-title="选择试验项目"
      :visible.sync="visible"
      :width="1000"
    >
      <div slot="formHeader">
        <a-form-model ref="rulePlanForms" :model="planForms" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
          <div id="dialogDistrictBox">
            <a-row>
              <a-col :span="12">
                <a-form-model-item prop="testProjectId" label="试验项目" style="margin-bottom: 10px;">
                  <selector
                    selectType="6"
                    placeholder="请选择试验项目"
                    v-model="planForms.testProjectId"
                    @getOption="
                      (e) => {
                         $set(planForms, 'testProjectName', e ? e.name: '')
                      }
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12" v-if="planForms.testProjectName && planForms.testProjectName.indexOf('其他') > -1">
                <a-form-model-item prop="otherExperimentProjectName" label=""  style="margin-bottom: 10px;">
                  <BaseInput
                    style="margin-left: 20px;"
                    placeholder="请输入具体的试验项目种类"
                    :maxLength="30"
                    v-model="planForms.otherExperimentProjectName"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item prop="number" label="试验项目编号"  style="margin-bottom: 10px;">
                  <BaseInput
                    placeholder="请输入试验项目编号"
                    :maxLength="30"
                    v-model="planForms.number"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item prop="specification" label="规格"  style="margin-bottom: 10px;">
                  <BaseInput
                    placeholder="请输入规格"
                    :maxLength="30"
                    v-model="planForms.specification"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item prop="applicationPlace" label="使用部位"  style="margin-bottom: 10px;">
                  <BaseInput
                    placeholder="请输入使用部位"
                    :maxLength="30"
                    v-model="planForms.applicationPlace"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="6" />
              <a-col :span="6" style="text-align: right;">
                <a-button
                  type="primary"
                  style="margin-right: 10px"
                  @click="planSearch"
                >
                  搜索
                </a-button>
                <a-button @click="planReset">
                  重置
                </a-button>
              </a-col>
            </a-row>
        </div>
        </a-form-model>
        <a-table
          row-key="id"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
          :columns="columns"
          :data-source="dataSource"
          :loading="requestLoading"
          bordered
          @change="planTableChange"
          :pagination="{
            current: pageNo,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSize: pageSize,
            showTotal: (total) => `共 ${total} 条数据`,
            total: totalSize
          }"
        />
      </div>
      <template slot="footer">
        <a-button
          type="primary"
          class="button_right"
          @click="visible = false"
        >
          关闭
        </a-button>
        <a-button
          type="primary"
          :disabled="selectedRowKeys.length === 0"
          @click="handleConfirm"
        >
          确认选择
        </a-button>
      </template>
    </DialogForm>
  </base-breadcrumb>
</template>

<script>
import { experimentTable, experimentPlan } from '@/api/quality/quality' // api
import Selector from '@/components/Select/Selector' // 通用下拉框
import DialogForm from '@/components/DialogForm' // 弹窗
import UploadList from '@/components/UploadList' // 文件上传
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    Selector,
    UploadList,
    DialogForm
  },
  data() {
    return {
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      // 盒子高度
      boxHeight: 0,
      loading: false,
      requestLoading: false, // 关联试验计划loading
      spinning: false,
      id: '',
      visible: false, // 试验计划弹窗显隐控件
      editModel: 0,
      planForms: {
        testProjectId: void 0,
        testProjectName: '',
        otherExperimentProjectName: '',
        number: '',
        specification: '',
        applicationPlace: '',
      },
      experimentTable: {}, // 试验台账表单
      selectedRowKeys: [], // 实验计划选中id集合
      selectedRow: [], // 实验计划选中对象集合
      projectInfo: {}, // 项目信息
      form: {}, // 表单信息
      dataSource: [], // 试验计划列表
      columns: [
        {
          title: '试验项目编号',
          dataIndex: 'number',
          ellipsis: true
        },
        {
          title: '试验项目',
          dataIndex: 'experimentProject',
          ellipsis: true,
          customRender(text, record, index) {
            if (record.experimentProject && record.experimentProject.indexOf('其他') > -1) {
              return record.experimentProject + (record.otherExperimentProjectName ? '-'+ record.otherExperimentProjectName : '')
            } else {
              return record.experimentProject
            }
          },
        },

        {
          title: '规格',
          dataIndex: 'specification',
          ellipsis: true
        },
        {
          title: '使用部位',
          dataIndex: 'applicationPlace',
          ellipsis: true
        }
      ], // 试验计划表头
      rules: {
        otherExperimentProjectName: [{ required: true, message: '请输入具体的试验项目种类', trigger: 'change' }],
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        specimenNumber: [{ required: true, whitespace: true, message: '请输入试件编号', trigger: 'change' }],
        experimentProject: [{ required: true, message: '请选择试验项目', trigger: 'change' }],
        varietiesKinds: [{ required: true, whitespace: true, message: '请输入品种/种类', trigger: 'change' }],
        specification: [{ required: true, whitespace: true, message: '请输入规格', trigger: 'change' }],
        originSite: [{ required: true, whitespace: true, message: '请输入产地厂别', trigger: 'change' }],
        place: [{ required: true, whitespace: true, message: '请输入部位', trigger: 'change' }],
        whetherToWitness: [{ required: true, message: '请选择是否见证', trigger: 'change' }],
        entryTime: [{ required: true, message: '请选择进场时间', trigger: 'change' }],
        inspectionTime: [{ required: true, message: '请选择送检时间', trigger: 'change' }],
        principalNo: [{ required: true, whitespace: true, message: '请输入委托编号', trigger: 'change' }],
        reportNo: [{ required: true, whitespace: true, message: '请输入报告编号', trigger: 'change' }],
        experimentResults: [{ required: true, whitespace: true, message: '请输入试验结果', trigger: 'change' }],
        archiveTime: [{ required: true, message: '请选择归档时间', trigger: 'change' }]
        // fileArrays: [{ type: 'array', required: true, message: '请上传试验报告', trigger: 'blur' }],
      },
      initFlag: false // 初始化文件监听
    }
  },
  watch: {
    'experimentTable.fileArrays'(e) {
      if (this.editModel != 2 && this.initFlag) {
        this.$nextTick(() => {
          this.$refs.experimentForm?.validateField('fileArrays')
        })
      }
    }
  },
  computed: {
    // 试验计划编号
    planItems() {
      return this.experimentTable?.details?.map((i) => i.number)?.join('；') || void 0
    },
  },
  mounted() {
    if (this.editModel != 0) {
      this.init()
    } else {
      this.$nextTick(() => {
        this.initFlag = true
      })
    }
  },
  methods: {
    selectOrg(val) {
      this.projectInfo.branchCompanyId = val[val.length-2].orgId
      this.$set(experimentTable, 'details', [])
      this.$set(experimentTable, 'place', 0)
      this.selectedRowKeys = []
      this.selectedRow = []
    },
    /**
     * @description: 试验计划复选项改变
     * @param {*} selectedRowKeys：选中项
     */
    onSelectChange(selectedRowKeys, selectedRow) {
      // console.log(selectedRowKeys, selectedRow)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    /**
     * @description: 关联试验计划后回调
     */
    handleConfirm() {
      if(this.selectedRow.length > 0) {
        this.$set(this.experimentTable, 'specification', this.selectedRow[0].specification)
        this.$set(this.experimentTable, 'experimentProject', this.selectedRow[0].experimentProjectId)
        if (!!this.selectedRow[0].otherExperimentProjectName) {
          this.$set(this.experimentTable, 'otherExperimentProjectName', this.selectedRow[0].otherExperimentProjectName)
        } else {
          this.$set(this.experimentTable, 'otherExperimentProjectName', '')
        }
        this.$set(this.experimentTable, 'experimentProjectName', this.selectedRow[0].experimentProject)
        this.$set(this.experimentTable, 'details', this.selectedRow)
        this.$set(this.experimentTable, 'place', this.selectedRow[0].applicationPlace)
      }
      this.visible = false
    },
    /**
     * @description: 打开选择试验项目弹窗
     */
    handleOpen() {
      this.requestLoading = true
      this.pageSize = 10
      this.pageNo = 1
      experimentPlan
        .getQueryDetail({
          recordId: this.id,
          projectId: this.projectInfo.projectId,
          pageSize: this.pageSize,
          pageNo: this.pageNo,
        })
        .then((res) => {
          this.requestLoading = false
          if (res.code === 200 && res.data?.length) {
            this.dataSource = res.data
            this.totalSize = res.totalSize
            this.visible = true
          } else {
            this.$message.warning('没有计划项可以关联！')
          }
        })
        .catch(() => {
          this.requestLoading = false
        })
    },
    // 初始化
    init() {
      this.spinning = true
      experimentTable
        .getDetail({
          id: this.id
        })
        .then((res) => {
          this.spinning = false
          if (res.code == 200) {
            this.projectInfo = res.data.projectInfo
            this.experimentTable = res.data.experimentTable
            if (res.data.experimentTable && res.data.experimentTable.details && res.data.experimentTable.details.length) {
              this.selectedRow = res.data.experimentTable.details[0]
              this.selectedRowKeys = [res.data.experimentTable.details[0].id]
            }
            this.$nextTick(() => {
              this.initFlag = true
            })
          }
        })
        .catch((res) => {
          this.spinning = false
        })
    },
    // 提交表单
    handleSubmit() {
      let that = this
      new Promise((resolve, reject) => {
        // 校验项目信息
        that.$refs.ruleForm.validate((res) => {
          if (res) {
            resolve(res)
          } else {
            reject()
          }
        })
      }).then((res) => {
        if (res) {
          // 校验试验信息
          that.$refs.experimentForm.validate((res) => {
            if (res) {
              let name = ['create', 'update'][that.editModel] // 动态取得api请求方法
              let form = {
                experimentTable: that.experimentTable,
                projectInfo: that.projectInfo
              }
              // 若为编辑则添加id
              if (that.editModel == 1) {
                form.id = that.id
              }
              // 加载框
              that.loading = true
              experimentTable[name](form)
                .then((res) => {
                  // if (res.code == 200 || res.data.code == 200) {
                  // 取消加载框
                  that.loading = false
                  that.$message.success(['添加', '编辑'][that.editModel] + '成功！')
                  // 关闭当前页
                  that.$multiTab.close()
                  // } else {
                  //   that.$message.warning(['添加', '编辑'][that.editModel] + '失败！')
                  // }
                })
                .catch((res) => {
                  // 取消加载框
                  that.loading = false
                })
            }
          })
        }
      })
    },
    planReset() {
      this.$refs.rulePlanForms.resetFields();
      this.pageNo = 1
      this.planLoadData()
    },
    planLoadData() {
      const values = this.planForms
      let queryParam = {}
      for (let key in values) {
        console.log(key, values[key])
        if (key != 'testProjectName' && values[key] !== undefined && values[key] !=='') {
          queryParam[key] = values[key]
        } // 过滤为undefined的数据
      }
      this.requestLoading = true
      experimentPlan
        .getQueryDetail({
          recordId: this.id,
          projectId: this.projectInfo.projectId,
          pageSize: this.pageSize,
          pageNo: this.pageNo,
          ...queryParam
        })
        .then((res) => {
          this.requestLoading = false
          if (res.code === 200) {
            this.dataSource = res.data || []
            this.totalSize = res.totalSize || 0
          }
        })
        .catch(() => {
          this.requestLoading = false
        })
    },
    planSearch() {
      this.pageNo = 1
      this.planLoadData()
    },
    planTableChange(pagination){
      this.pageNo = pagination.current
      this.pageSize = pagination.pageSize
      this.planLoadData()
    },
  }
}
</script>
